//
//  HttpDownloader.m
//  Invaders
//
//  Created by Chris Greening on 06/07/2009.
//  Copyright 2009 CMG Research. All rights reserved.
//

#import "HttpDownloader.h"


@implementation HttpDownloader

@synthesize delegate;

+ (NSString *)escapeChars:(NSString *)theString {
    NSString *reserved = @".<>\":/?#[]@!$&'()*+,;=\n\r\t ";
    return [((NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)theString, NULL, (CFStringRef)reserved, kCFStringEncodingUTF8)) autorelease];
}

- (void) dealloc
{
	[resultData release];
	[super dealloc];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[resultData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	if(((NSHTTPURLResponse *) response).statusCode!=200) {
		[connection cancel];
		if(delegate!=nil && [delegate respondsToSelector:@selector(downloaderFailed:)]) {
			[delegate downloaderFailed:self];
			[resultData release];
			resultData=nil;
			theConnection=nil;
		}
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	if(delegate!=nil && [delegate respondsToSelector:@selector(downloaderFailed:)]) {
		[delegate downloaderFailed:self];
	}
	[resultData release];
	resultData=nil;
	theConnection=nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	if(delegate!=nil && [delegate respondsToSelector:@selector(downloader:downloadedData:)]) {
		[delegate downloader:self downloadedData:resultData];
	}
	[resultData release];
	resultData=nil;
	theConnection=nil;
}


-(void) downloadDataFromUrl:(NSString *) urlString delegate:(id) theDelegate {
	// already downloading something
	if(theConnection!=nil) return;
	
	self.delegate=theDelegate;
	NSURL *url = [NSURL URLWithString:urlString];
	NSURLRequest *request=[NSURLRequest requestWithURL:url  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
	theConnection=[NSURLConnection connectionWithRequest:request delegate:self];
	if(theConnection!=nil) {
		resultData=[[NSMutableData alloc] init];
	} else {
		if(delegate!=nil && [delegate respondsToSelector:@selector(downloaderFailed:)]) {
			[delegate downloaderFailed:self];
		}
	}
}

-(void) cancelDownload {
	[theConnection cancel];
	[resultData release];
	resultData=nil;
}

@end
